$input v_fragPos, v_normal, v_texcoord0


#include "../../bgfx/examples/common/common.sh"

SAMPLERCUBE(s_texLod, 3);
SAMPLERCUBE(s_texIrr, 4);

uniform vec4 u_lightColor;
uniform vec4 u_environment;  // { doEnvSpecular, doEnvDiffuse, mipLevel, 0.0f };

struct Light {
	vec3 color;
};

void main()
{
	Light light;
	light.color = u_lightColor.xyz;

	vec3 normal = normalize(v_normal);

	float mip = u_environment.z;
	
	vec3 irradiance  = toLinear(textureCube(s_texIrr, normal).xyz);
	vec3 albedo = light.color;
	vec3 envDiffuse = irradiance * albedo * u_environment.y;

	float envFresnel = 0.562f; // iron f0
	vec3 reflectDir = -reflect(-v_fragPos, normal);
	vec3 radiance    = toLinear(textureCubeLod(s_texLod, reflectDir, mip).xyz);
	vec3 envSpecular = envFresnel * radiance * u_environment.x;

	vec3 color = envDiffuse + envSpecular;
	color = color / (color + vec3(1.0, 1.0, 1.0));  

	gl_FragColor.xyz = color;
	gl_FragColor.w = 1.0;
	gl_FragColor = toGamma(gl_FragColor);
}
